<?php

namespace App\HttpController\Api;

use App\HttpController\BaseController;
use App\Model\UsersModel;
use App\Utility\MiniProgram;
use Carbon\Carbon;

class Login extends BaseController
{

    public function index(){
        try{
            $request = $this->request();
            $code = $request->getRequestParam('code');
            $mini = new MiniProgram();
            $session = $mini->session($code);
            $model = new UsersModel();
            $user = $model->findData($session['openid']);
            if(empty($user)){
                //新增用户
                $insert = [
                    'openid' => $session['openid'],
                    'reg_at' => Carbon::now(),
                    'login_at' => Carbon::now(),
                ];
                $id = $model->create($insert);
                $user = array_merge($insert,['id'=>$id]);
            }else{
                //更新登录时间
                $update = [
                    'id' => $user['id'],
                    'login_at' => Carbon::now(),
                ];
                $model->update($update);
            }
            return $this->writeJson(0,$user);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }
}
